import { defineStore, storeToRefs } from "pinia";
import { ref } from "vue";
import { usePersistStore, useDeskStore } from "@/stores";
import { getInfo, testStr } from "@/utils/function";
//表格数据读取相关
import * as XLSX from "xlsx";
import { readFileAsBinaryString } from "@/utils/readFile";
import {
  addExtraService,
  delExtraService,
  getExtraById,
  getExtraListService,
  modifyExtraInfoService,
  modifyExtraService,
  showPlaceService,
  uploadExtraService,
} from "@/api/extraApi";
export const useExtraStore = defineStore("extra", () => {
  const persistStore = usePersistStore();
  const deskStore = useDeskStore();
  const { getAvailableRfids, getAllRfids, getOverview } = deskStore;
  const { extraList, extraTotal, userInfo } = storeToRefs(persistStore);

  //备料信息的条件查询
  const queryData = ref({
    page: 1,
    pageSize: 5,
    name: "",
  });
  const loading = ref(false);
  //备料信息分页查询请求
  const getextras = async () => {
    loading.value = true;
    const res = await getExtraListService(queryData.value);
    extraList.value = res.data.rows;
    extraTotal.value = res.data.total;
    loading.value = false;
  };
  if (userInfo.value.token != "") {
    getextras();
  }
  //备料信息查询表单的清空
  const clearQueryData = () => {
    queryData.value = {
      page: 1,
      pageSize: 5,
      name: "",
    };
    getextras();
  };
  //备料信息查询表单的提交
  const submitQuery = () => {
    getextras();
  };

  //备料信息分页相关
  const tobSizeChange = (pageSize) => {
    queryData.value.pageSize = pageSize;
    queryData.value.page = 1;
    getextras();
  };
  const tobPageChange = (page) => {
    queryData.value.page = page;
    getextras();
  };

  //备料信息的多选查找(电子标签)
  const tobTable = ref();
  const rfids = ref([]); //存放多选的电子标签值

  const multipleChoice = (value) => {
    rfids.value = [];
    value.forEach((item) => {
      rfids.value.push(item.rfid);
    });
  };
  //备料信息多选查找时候的位置显示弹窗
  const showTobaccoPlace = ref(false);
  //根据rfid号查找到的详细信息
  //TODO:根据rfid详细信息展示位置信息
  const rfidInfo = ref([]);
  //备料位置显示请求
  const showPlace = async () => {
    const res = await showPlaceService(rfids.value);
    rfidInfo.value = res.data;
    console.log(rfidInfo.value);
    ElMessage.success("查找成功");
  };
  const searchByrfids = () => {
    showPlace();
    tobTable.value.clearSelection();
    showTobaccoPlace.value = true;
  };

  //备料信息备注的编辑
  const infoChecked = ref([]);
  const infoCheckedChange = () => {};
  const commentVisible = ref(false);
  const index = ref();
  const changeComment = (idx, row) => {
    commentVisible.value = true;
    index.value = row.id;
  };
  //关闭备注的对话框
  const closeDialog = () => {
    infoChecked.value = [];
    commentVisible.value = false;
  };

  //备料信息备注编辑请求
  const modifyextraInfo = async (data) => {
    const res = await modifyExtraInfoService(data);
    getextras();
    ElMessage.success(res.message);
  };
  //提交备注信息
  const submitComment = () => {
    if (infoChecked.value.length !== 0) {
      const tempInfo = getInfo(infoChecked.value);
      modifyextraInfo({
        id: index.value,
        info: tempInfo,
      });
    }
    closeDialog();
  };
  //备料信息的删除请求
  const delEXtra = async (data) => {
    const res = await delExtraService(data);
    getextras();
    getAvailableRfids();
    //getOverview();
    ElMessage.success(res.message);
  };
  //备料信息的删除
  const tobDelete = (index, row) => {
    ElMessageBox.confirm("你确定要删除这条信息吗?", "温馨提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        delEXtra(row);
      })
      .catch(() => {
        ElMessage.success("取消删除");
      });
  };

  //备料信息编辑和添加
  const drawerTitle = ref("");
  const drawerVisible = ref(false);

  const num = ref(0); //1表示添加,2表示编辑

  //备料信息的单条添加
  const addForm = ref();
  const choseRfid = ref(true);

  const addDrawerVisible = ref(false);
  const addTobaccoData = ref({
    id: "",
    rfid: null,
    name: "",
    location: "",
    year: "",
    part: "",
    evaluate: null,
    info: "",
  });
  const addTobaccRules = {
    name: [{ required: true, message: "请输入备料信息名称", trigger: "blur" }],
    location: [
      { required: true, message: "请输入备料信息产地", trigger: "blur" },
    ],
    rfid: [{ required: true, message: "请选择单料rfid号", trigger: "change" }],
    year: [
      { required: true, message: "请输入备料信息年份", trigger: "blur" },
      { pattern: /^\d{4}$/, message: "请输入正确的年份", trigger: "blur" },
    ],
    part: [{ required: true, message: "请输入备料信息名称", trigger: "blur" }],
    evaluate: [
      { required: true, message: "请选择备料信息评估状态", trigger: "change" },
    ],
  };

  const addTobacco = () => {
    addDrawerVisible.value = true;
    num.value = 1;
    drawerTitle.value = "备料信息添加";
    choseRfid.value = true;
  };
  //根据id查询备料信息请求
  const getextraById = async (id) => {
    const res = await getExtraById(id);
    addTobaccoData.value = res.data;
  };
  //编辑备料信息请求
  const modifyextra = async (data) => {
    const res = await modifyExtraService(data);
    getextras();
    ElMessage.success(res.message);
  };
  //添加备料信息请求
  const addextra = async (data) => {
    const res = await addExtraService(data);
    getextras();
    getAvailableRfids();
    //getOverview();
    ElMessage.success(res.message);
  };
  //备料信息的编辑
  const tobEdit = (index, row) => {
    addDrawerVisible.value = true;
    drawerTitle.value = "备料信息编辑";
    choseRfid.value = false;
    getextraById(row.id);
  };
  //添加表单的清空
  const clearAddData = () => {
    addTobaccoData.value = {
      rfid: null,
      name: "",
      location: "",
      year: "",
      part: "",
      evaluate: null,
      info: "",
    };
    infoChecked.value = [];
  };

  //备料信息单条添加和编辑的提交
  const submitEvent = async () => {
    await addForm.value.validate();
    if (infoChecked.value.length != 0) {
      addTobaccoData.value.info = getInfo(infoChecked.value);
    }
    if (num.value == 1) {
      addextra(addTobaccoData.value);
    } else {
      modifyextra(addTobaccoData.value);
    }

    addDrawerVisible.value = false;
    infoChecked.value = [];
    clearAddData();
  };

  //============================================================================
  //备料信息数据的导入
  const uploadDraw = ref(false);
  const openUploadDraw = () => {
    uploadDraw.value = true;
    drawerTitle.value = "备料信息导入";
  };
  // 表格数据的上传
  const uploadTableData = ref([]);
  const baseTableData = ref([]); //基本数据
  const file = ref();
  //更改基础信息表传入的字段名
  const baseCharacters = {
    id: { text: "id", type: "string" },
    rfid: { text: "rfid号", type: "string" },
    name: { text: "名称", type: "string" },
    location: { text: "产地", type: "string" },
    year: { text: "年份", type: "string" },
    part: { text: "部位", type: "string" },
    evaluate: { text: "评估状态", type: "number" },
    info: { text: "备注", type: "string" },
  };
  const errorNum = ref(0);
  const showUploadTable = async (ev) => {
    //每次选择文件都把之前文件清空
    uploadTableData.value = [];
    errorNum.value = 0;
    file.value = ev.raw; //这里面就是数据

    // 将file变成二进制读取到的
    let data = await readFileAsBinaryString(file.value);
    // 将得到的二进制转化一下
    let workbook = XLSX.read(data, { type: "binary" });

    // 最后把数据转成json格式的
    let worksheet = workbook.Sheets[workbook.SheetNames[0]]; //这里是表格的名字,这里取第一个表格,1就是第二个表格数据

    //将得到的worksheet转化为json格式
    data = XLSX.utils.sheet_to_json(worksheet);

    //循环遍历得到的数据，将传入的字段更改为后台需要的字段
    data.forEach((item) => {
      let obj = {};
      for (let key in baseCharacters) {
        let temp = baseCharacters[key], //变量只能用[]来访问
          text = temp.text,
          type = temp.type;
        let value = item[text];
        if (value) {
          if (testStr(value)) {
            value = "*****";
            errorNum.value++;
          } else {
            if (type == "string") {
              value = String(value);
            } else if (type == "number") {
              value = Number(value);
            } else if (type == "array") {
              if (value.includes(",")) {
                value = value.split(",");
              } else if (value.includes("，")) {
                value = value.split("，");
              }
            }
          }
        }
        obj[key] = value;
      }
      uploadTableData.value.push(obj);
    });
    //获取表格数据
    baseTableData.value = uploadTableData.value;
    if (errorNum.value > 0) {
      ElMessage.error("导入数据存在问题，请仔细检查后再导入");
    }
  };
  //上传文件的清除
  const delUpload = () => {
    errorNum.value = 0;
    if (baseTableData.value.length) {
      baseTableData.value = [];
    }
    if (detailTableData.value.length) {
      detailTableData.value = [];
    }
  };
  //文件上传请求
  const uploadExtra = async () => {
    const formData = new FormData();
    formData.append("file", file.value);
    const res = await uploadExtraService(formData);
    getextras();
    //getOverview();
    getAllRfids();
    ElMessage.success(res.message);
  };
  //文件上传
  const submitUpload = () => {
    uploadExtra();
    file.value = null;
    uploadTableData.value = [];
    baseTableData.value = [];
    uploadDraw.value = false;
  };
  //============================================================================
  return {
    queryData,
    commentVisible,
    infoChecked,
    drawerVisible,
    drawerTitle,
    tobTable,
    showTobaccoPlace,
    addDrawerVisible,
    addTobaccoData,
    addTobaccRules,
    addForm,
    uploadDraw,
    uploadTableData,
    baseTableData,
    loading,
    choseRfid,
    rfidInfo,
    openUploadDraw,
    submitUpload,
    delUpload,
    showUploadTable,
    multipleChoice,
    searchByrfids,
    infoCheckedChange,
    changeComment,
    closeDialog,
    clearQueryData,
    clearAddData,
    tobSizeChange,
    tobPageChange,
    tobDelete,
    submitComment,
    submitQuery,
    submitEvent,
    addTobacco,
    tobEdit,
    getextras,
  };
});
